package cn.com.shopec.erp.multiChannel.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.JdException;
import com.jd.open.api.sdk.domain.delivery.LogisticsCompanies;
import com.jd.open.api.sdk.domain.delivery.LogisticsCompany;
import com.jd.open.api.sdk.request.delivery.DeliveryLogisticsGetRequest;
import com.jd.open.api.sdk.request.order.OrderSopOutstorageRequest;
import com.jd.open.api.sdk.response.delivery.DeliveryLogisticsGetResponse;
import com.jd.open.api.sdk.response.order.OrderSopOutstorageResponse;

import cn.com.shopec.erp.common.constant.SZSCMConstant;
import cn.com.shopec.erp.common.page.PageFinder;
import cn.com.shopec.erp.common.page.PageQuery;
import cn.com.shopec.erp.common.utils.DateUtil;
import cn.com.shopec.erp.common.utils.LogicUtil;
import cn.com.shopec.erp.common.utils.NoUtil;
import cn.com.shopec.erp.common.utils.StringUtil;
import cn.com.shopec.erp.multiChannel.common.MultiChannelConfig;
import cn.com.shopec.erp.multiChannel.common.MultiChannelConstant;
import cn.com.shopec.erp.multiChannel.dao.IChannelOrderDao;
import cn.com.shopec.erp.multiChannel.dao.IChannelOrderItemDao;
import cn.com.shopec.erp.multiChannel.dao.IChannelOrderReceiverDao;
import cn.com.shopec.erp.multiChannel.dao.IProductPackageDao;
import cn.com.shopec.erp.multiChannel.dao.IProductPackageItemDao;
import cn.com.shopec.erp.multiChannel.entity.ChannelOrder;
import cn.com.shopec.erp.multiChannel.entity.ChannelOrderItem;
import cn.com.shopec.erp.multiChannel.entity.ChannelOrderReceiver;
import cn.com.shopec.erp.multiChannel.entity.JDChannelOrderInfo;
import cn.com.shopec.erp.multiChannel.entity.ProductPackage;
import cn.com.shopec.erp.multiChannel.entity.ProductPackageItem;
import cn.com.shopec.erp.multiChannel.service.IChannelOrderService;
import cn.com.shopec.erp.multiChannel.vo.ChannelOrderVo;
import cn.com.shopec.erp.product.dao.IProductStockDao;
import cn.com.shopec.erp.product.entity.ProductStock;
import cn.com.shopec.erp.product.vo.ProductStockVo;
import cn.com.shopec.erp.purchase.entity.StockPurchase;
import cn.com.shopec.erp.stock.commo.ObjectUtil;
import cn.com.shopec.erp.stock.commo.StockProductException;
import cn.com.shopec.erp.stock.dao.IStockOutDao;
import cn.com.shopec.erp.stock.entity.StockOut;
import cn.com.shopec.erp.system.dao.IParamsDao;
import cn.com.shopec.erp.system.entity.Parameter;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class ChannelOrderServiceImpl implements IChannelOrderService {

	@Resource
	private IParamsDao iparamsDao;

	@Resource
	private IChannelOrderDao channelOrderDao;

	@Resource
	private IStockOutDao stockOutDao;

	@Resource
	private IChannelOrderItemDao channelOrderItemDao;

	@Resource
	private IChannelOrderReceiverDao channelOrderReceiverDao;

	@Resource
	private IProductPackageDao productPackageDao;

	@Resource
	private IProductPackageItemDao productPackageItemDao;

	@Resource
	private IProductStockDao productStockDao;

	public PageFinder<ChannelOrder> channelOrderPageList(ChannelOrderVo channelOrderVo, PageQuery pageQuery)
			throws ParseException {
		DetachedCriteria detachedCriteria = channelOrderDao.createCriteria();
		if (channelOrderVo != null) {
			if (StringUtil.isExist(channelOrderVo.getChannelOrderId())) {
				detachedCriteria.add(Restrictions.eq("channelOrderId", channelOrderVo.getChannelOrderId()));
			}
			if (StringUtil.isExist(channelOrderVo.getChannelOrderType())) {
				detachedCriteria.add(Restrictions.eq("channelOrderType", channelOrderVo.getChannelOrderType()));
			}
			if (StringUtil.isExist(channelOrderVo.getOrderType())) {
				detachedCriteria.add(Restrictions.eq("orderType", channelOrderVo.getOrderType()));
			}
			if (StringUtil.isExist(channelOrderVo.getDeliveryState())) {
				detachedCriteria.add(Restrictions.eq("deliveryState", channelOrderVo.getDeliveryState()));
			}
			if (StringUtil.isExist(channelOrderVo.getPayState())) {
				detachedCriteria.add(Restrictions.eq("payState", channelOrderVo.getPayState()));
			}
			if (StringUtil.isExist(channelOrderVo.getPayType())) {
				detachedCriteria.add(Restrictions.eq("payType", channelOrderVo.getPayType()));
			}
			if (StringUtil.isExist(channelOrderVo.getOrderStartTime())) {
				detachedCriteria.add(Restrictions.ge("orderStartTime", channelOrderVo.getOrderStartTime()));
			}
			if (StringUtil.isExist(channelOrderVo.getOrderEndTime())) {
				String endTime = DateUtil.getDateNextDay(channelOrderVo.getOrderEndTime());
				detachedCriteria.add(Restrictions.le("orderStartTime", endTime));
			}
			if (StringUtil.isExist(channelOrderVo.getReturnOrder())) {
				String[] returnOrder = channelOrderVo.getReturnOrder().split(",");
				detachedCriteria.add(Restrictions.in("returnOrder", returnOrder));
			}
			// 收货人
			if (LogicUtil.isNotNullAndEmpty(channelOrderVo.getReceiverName())) {
				detachedCriteria
						.add(Restrictions.like("receiverName", "%" + channelOrderVo.getReceiverName().trim() + "%"));
			}
			if (LogicUtil.isNotNullAndEmpty(channelOrderVo.getReceiverPhone())) {
				detachedCriteria
						.add(Restrictions.like("receiverPhone", "%" + channelOrderVo.getReceiverPhone().trim() + "%"));
			}
			if (StringUtil.isExist(channelOrderVo.getReturnState())) {
				if ("0".equals(channelOrderVo.getReturnState())) {
					detachedCriteria.add(Restrictions.isNull("returnState"));
				} else {
					detachedCriteria.add(Restrictions.eq("returnState", channelOrderVo.getReturnState()));
				}
			}
		}
		detachedCriteria.addOrder(Order.desc("orderStartTime"));
		return channelOrderDao.pagedByCriteria(detachedCriteria, pageQuery.getPage(), pageQuery.getPageSize());
	}

	@Override
	public PageFinder<ChannelOrderItem> channelOrderItemPageList(ChannelOrderVo channelOrderVo, PageQuery pageQuery) {
		DetachedCriteria detachedCriteria = channelOrderItemDao.createCriteria();
		if (channelOrderVo != null) {
			if (StringUtil.isExist(channelOrderVo.getChannelOrderId())) {
				detachedCriteria.add(Restrictions.eq("channelOrderId", channelOrderVo.getChannelOrderId()));
			}
		}
		return channelOrderItemDao.pagedByCriteria(detachedCriteria, pageQuery.getPage(), pageQuery.getPageSize());
	}

	@Override
	public ChannelOrderReceiver getChannelOrderReceiver(String channelOrderId) {
		return channelOrderReceiverDao.get("channelOrderId", channelOrderId);
	}
	
	@Override
	public ChannelOrder getChannelOrder(String id) {
		return channelOrderDao.get("id", id);
	}

	@Override
	public PageFinder<Map<String, Object>> productPackagePageList(ChannelOrderVo channelOrderVo, PageQuery pageQuery) {
		return productPackageDao.productPackagePaged(channelOrderVo, pageQuery);
	}

	@Transactional
	@Override
	public String createProductPackage(ChannelOrderVo channelOrderVo) {
		String msg = SZSCMConstant.SUCCESS;
		try {
			if (channelOrderVo != null) {
				ProductPackage productPackage = new ProductPackage();
				if (StringUtil.isExist(channelOrderVo.getChannelOrderId())) {
					productPackage.setChannelOrderId(channelOrderVo.getChannelOrderId());
				}
				List<ChannelOrderItem> itemlist = channelOrderItemDao.findByProperty("channelOrderId",
						channelOrderVo.getChannelOrderId());
				Set whNos = new HashSet();
				Set allWhNo = new HashSet();
				int i = 0;
				for (ChannelOrderItem item : itemlist) {
					ProductStockVo productStockVo = new ProductStockVo();
					productStockVo.setProdNo(item.getItemNum());
					if (item.getItemTotal() != null) {
						productStockVo.setQualifiedQuantity(item.getItemTotal().longValue());
					}
					List<Map<String, Object>> psList = productStockDao.productStockList(productStockVo);
					if (psList != null && !psList.isEmpty()) {
						Set whTemp = new HashSet();
						for (Map<String, Object> map : psList) {
							if (Long.valueOf(map.get("qualifiedQuantity").toString()) >= productStockVo
									.getQualifiedQuantity()) {
								whTemp.add(map.get("whNo"));
							}
						}
						if (i == 0) {
							whNos.addAll(whTemp);
						} else {
							allWhNo.addAll(whNos);
							whNos.retainAll(whTemp);
						}
						if (whNos.isEmpty()) {
							msg = SZSCMConstant.FAIL;
							break;
						}
					}
					i++;
				}
				if (whNos.isEmpty()) {
					msg = SZSCMConstant.FAIL;
				}
				if (!SZSCMConstant.FAIL.equals(msg)) {
					String whNo = "";
					if (!whNos.isEmpty()) {
						Iterator it = whNos.iterator();
						if (it.hasNext()) {
							whNo = it.next().toString();
						}
					}
					String prodPackageNo = new Date().getTime() + "";
					productPackage.setCreateTime(new Date());
					productPackage.setDeliveryState(0);
					productPackage.setProdPackageNo(prodPackageNo);
					productPackage.setWhNo(whNo);
					if (StringUtil.isExist(channelOrderVo.getOperatorId())) {
						productPackage.setOperatorId(channelOrderVo.getOperatorId());
					}
					productPackageDao.save(productPackage);

					ProductStockVo vo = new ProductStockVo();
					for (ChannelOrderItem item : itemlist) {
						vo.setProdNo(item.getItemNum());
						vo.setWhNo(whNo);
						List<ProductStock> pslist = productStockDao.getProductStockList(vo);
						Long total = item.getItemTotal().longValue();
						for (ProductStock ps : pslist) {
							Long qualifiedQuantity = (ps.getPreOccupyQuantity() != null ? ps.getPreOccupyQuantity() : 0)
									+ (ps.getQualifiedQuantity() != null ? ps.getQualifiedQuantity() : 0);
							ProductPackageItem productPackageItem = new ProductPackageItem();
							productPackageItem.setProdPackageNo(prodPackageNo);
							productPackageItem.setProdNo(item.getItemNum());
							productPackageItem.setWhNo(whNo);
							productPackageItem.setSupNo(ps.getSupNo());
							productPackageItem.setPrice(
									BigDecimal.valueOf(item.getItemPrice() != null ? item.getItemPrice() : 0.00));
							productPackageItem.setProdName(item.getSkuName());
							if (ps.getQualifiedQuantity() - total >= 0) {
								ps.setQualifiedQuantity(qualifiedQuantity);
								ps.setPreOccupyQuantity(
										(ps.getPreOccupyQuantity() != null ? ps.getPreOccupyQuantity() : 0) + total);
								productPackageItem.setTotal(total);
								productStockDao.update(ps);
								productPackageItemDao.save(productPackageItem);
								break;
							} else {
								total = total - ps.getQualifiedQuantity();
								productPackageItem.setTotal(ps.getQualifiedQuantity());
								ps.setPreOccupyQuantity(
										(ps.getPreOccupyQuantity() != null ? ps.getPreOccupyQuantity() : 0)
												+ (ps.getQualifiedQuantity() != null ? ps.getQualifiedQuantity() : 0));
								ps.setQualifiedQuantity(qualifiedQuantity);
								productStockDao.update(ps);
								productPackageItemDao.save(productPackageItem);
							}
						}
					}

					ChannelOrder channelOrder = new ChannelOrder();
					channelOrder.setChannelOrderId(channelOrderVo.getChannelOrderId());
					channelOrder.setOrderState("12");// 已生成商品包裹单
					int count = channelOrderDao.updateByChannelOrderId(channelOrder);
					if (count == 0) {
						msg = SZSCMConstant.FAIL;
					}
				}
			} else {
				msg = SZSCMConstant.FAIL;
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = SZSCMConstant.FAIL;
		}
		return msg;
	}

	@Override
	public PageFinder productPackageItemPageList(ChannelOrderVo channelOrderVo, PageQuery pageQuery) {
		return productPackageItemDao.productPackageItemPaged(channelOrderVo, pageQuery);
	}

	/**
	 * 
	 * @param prodPackageNo
	 * @param state
	 *            0.未出库 1.生成出库单 2.已出库
	 * @return
	 * @throws Exception
	 */
	@Transactional
	@Override
	public String updateProductPactkageState(String prodPackageNo, int state) throws Exception {
		if (StringUtil.isExist(prodPackageNo)) {
			ProductPackage ProductPackage = productPackageDao.get("prodPackageNo", prodPackageNo);
			if (LogicUtil.isNotNull(ProductPackage)) {
				ProductPackage.setState(state);
				if (state == 1) {
					updateMultiChannel(ProductPackage.getChannelOrderId(),
							MultiChannelConstant.CHANNEL_ORDER_STATE_STOCKOUT_CREATE,
							MultiChannelConstant.CHANNEL_DELIVERY_STATE_NO);
				} else {
					ProductPackage.setDeliveryState(1);// 0.未发货 1.已发货
					ProductPackage.setDeliveryTime(new Date());
					List<ProductPackage> productPackages = getChannelAllPackage(ProductPackage.getChannelOrderId());
					List<StockOut> stockOuts = getChannelAllStockOutInfo(productPackages);
					if (stockOuts != null) {// 当stockOut不为null时则代表包裹已全部出库
						updateMultiChannel(ProductPackage.getChannelOrderId(),
								MultiChannelConstant.CHANNEL_ORDER_STATE_DELIVERY_OK,
								MultiChannelConstant.CHANNEL_DELIVERY_STATE_YES);
						setThirdPartyChannelOrderState(ProductPackage.getChannelOrderId(), stockOuts);
					} else {
						updateMultiChannel(ProductPackage.getChannelOrderId(),
								MultiChannelConstant.CHANNEL_ORDER_STATE_SECTION_STOCKOUT,
								MultiChannelConstant.CHANNEL_DELIVERY_STATE_YES);
					}
				}
				ProductPackageItem productPackageItem = new ProductPackageItem();
				productPackageItem.setProdPackageNo(prodPackageNo);
				productPackageItem.setState(state);// 1.生成出库单 2.已出库
				productPackageItemDao.updateProductPackageItem(productPackageItem);
				productPackageDao.update(ProductPackage);
				return SZSCMConstant.SUCCESS;
			}
		}
		return SZSCMConstant.FAIL;
	}

	/**
	 * 设置第三方状态
	 * @param channelOrderId
	 * @param stockOuts
	 * @return
	 * @throws JdException
	 */
	@Transactional
	private boolean setThirdPartyChannelOrderState(String channelOrderId, List<StockOut> stockOuts) throws JdException {
		ChannelOrder channelOrder = channelOrderDao.get("channelOrderId", channelOrderId);
		if (ObjectUtil.eq(channelOrder.getChannelOrderType(), "0")) {// 0.京东1淘宝2天猫
			return setJDChannelOrderState(channelOrderId, stockOuts);
		}
		return false;
	}

	/**
	 * 设置京东状态
	 * 
	 * @param channelOrderId
	 * @param stockOuts
	 * @return
	 * @throws JdException
	 */
	@Transactional
	private boolean setJDChannelOrderState(String channelOrderId, List<StockOut> stockOuts) throws JdException {
		JDChannelOrderInfo channelOrderInfo = getJDchannelOrderInfo(channelOrderId, stockOuts);
		if (channelOrderInfo != null) {
			String serverUrl = MultiChannelConfig.getString("jd.serverUrl");
			String accessToken = MultiChannelConfig.getString("jd.accessToken");
			String appKey = MultiChannelConfig.getString("jd.appKey");
			String appSecret = MultiChannelConfig.getString("jd.appSecret");
			JdClient client = new DefaultJdClient(serverUrl, accessToken, appKey, appSecret);
			OrderSopOutstorageRequest request = new OrderSopOutstorageRequest();
			request.setLogisticsId(channelOrderInfo.getLogisticsId());
			request.setWaybill(channelOrderInfo.getWaybill());
			request.setOrderId(channelOrderInfo.getOrderId());
			OrderSopOutstorageResponse response = client.execute(request);
			if (response.getCode().equals("0")) {// 返回的code为0时则代表出错
				return true;
			}
			throw new StockProductException(response.getZhDesc());
		}
		return false;
	}

	/**
	 * 得到订单下所有出库单的物流信息
	 * @param channelOrderId
	 * @param stockOuts
	 * @return
	 * @throws JdException
	 */
	private JDChannelOrderInfo getJDchannelOrderInfo(String channelOrderId, List<StockOut> stockOuts)
			throws JdException {
		List<LogisticsCompany> logisticsCompanys = getJDLogisticsInfo();
		JDChannelOrderInfo channelOrderInfo = new JDChannelOrderInfo();
		channelOrderInfo.setOrderId(channelOrderId);
		Map<Long, String> map = new HashMap<Long, String>();// key为lgoisticsId,value为waybill。迭代拼接物流信息
		for (StockOut stockOut : stockOuts) {
			if (ObjectUtil.eq(stockOut.getProductFetchType(), SZSCMConstant.PRODUCT_FETCH_TYPE_2)) {
				for (LogisticsCompany logisticsCompany : logisticsCompanys) {
					if (ObjectUtil.eq(logisticsCompany.getLogisticsName(), stockOut.getLogisticsName())) {
						Long lgoisticsId = logisticsCompany.getLogisticsId();
						String waybill = map.get(lgoisticsId);
						if (waybill == null) {
							map.put(lgoisticsId, stockOut.getLogisticsOrder());
						} else {
							map.put(lgoisticsId, waybill + "," + stockOut.getLogisticsOrder());
						}
						break;
					}
				}
			}
		}
		String lgoisticsId = "";
		String waybill = "";
		for (Long key : map.keySet()) {
			lgoisticsId += key + "|";
			waybill += map.get(key) + "|";
		}
		if (lgoisticsId.length() > 0 && waybill.length() > 0) {
			channelOrderInfo.setLogisticsId(lgoisticsId.substring(0, lgoisticsId.length() - 1));// 移除拼接的字符串最后一个多余的字符:'|'
			channelOrderInfo.setWaybill(waybill.substring(0, waybill.length() - 1));
		} else {// 如果为空时则返回自取信息
			Parameter parameter = iparamsDao.get("paramKey", SZSCMConstant.CHANNEL_ORDER_DEFAULT_PARAMETER_KEY);
			for (LogisticsCompany logisticsCompany : logisticsCompanys) {
				if (ObjectUtil.eq(logisticsCompany.getLogisticsName(), parameter.getParamValue())) {
					channelOrderInfo.setLogisticsId(lgoisticsId);
					channelOrderInfo.setWaybill("");
				}
			}
		}
		return channelOrderInfo;
	}

	/**
	 * 获取京东物流设置的信息
	 * 
	 * @return
	 * @throws JdException
	 */
	private List<LogisticsCompany> getJDLogisticsInfo() throws JdException {
		String serverUrl = MultiChannelConfig.getString("jd.serverUrl");
		String accessToken = MultiChannelConfig.getString("jd.accessToken");
		String appKey = MultiChannelConfig.getString("jd.appKey");
		String appSecret = MultiChannelConfig.getString("jd.appSecret");
		JdClient client = new DefaultJdClient(serverUrl, accessToken, appKey, appSecret);
		DeliveryLogisticsGetRequest request = new DeliveryLogisticsGetRequest();
		DeliveryLogisticsGetResponse response = client.execute(request);
		LogisticsCompanies logisticsCompanies = response.getLogisticsCompanies();
		return logisticsCompanies.getLogisticsList();
	}

	/**
	 * 获取订单下所有包裹单的出库信息（如果订单下有任意包裹单未完成出库时，则返回null）
	 * 
	 * @param productPackages
	 * @return
	 */
	private List<StockOut> getChannelAllStockOutInfo(List<ProductPackage> productPackages) {
		DetachedCriteria detachedCriteria = stockOutDao.createCriteria();
		Disjunction disjunction = Restrictions.disjunction();
		int counter = 0;
		for (ProductPackage productPackage : productPackages) {
			if (ObjectUtil.eq(productPackage.getDeliveryState(), 1)) {// 判断包裹单是否已出库
				disjunction.add(Restrictions.eq("stockOutTypeNo", productPackage.getProdPackageNo()).ignoreCase());
				counter++;
			}
		}
		if (counter == productPackages.size()) {// 判断已出库包裹单数量是否等于订单分包后的数量（既全部出库）
			detachedCriteria.add(Restrictions.eq("stockOutType", SZSCMConstant.STOCKOUT_TYPE_1));
			detachedCriteria.add(disjunction);
			return stockOutDao.findByCriteria(detachedCriteria);
		}
		return null;
	}

	/**
	 * 得到所有订单下的包裹单
	 * 
	 * @param channelOrderId
	 * @return
	 */
	private List<ProductPackage> getChannelAllPackage(String channelOrderId) {
		DetachedCriteria detachedCriteria = productPackageDao.createCriteria();
		detachedCriteria.add(Restrictions.eq("channelOrderId", channelOrderId));
		return productPackageDao.findByCriteria(detachedCriteria);
	}

	@Transactional
	private void updateMultiChannel(String channelOrderId, String orderState, String deliveryState) throws Exception {
		ChannelOrder channelOrder = channelOrderDao.get("channelOrderId", channelOrderId);
		channelOrder.setChannelOrderId(channelOrderId);
		channelOrder.setDeliveryState(deliveryState);
		channelOrder.setOrderState(orderState);// 已生成商品包裹单
		channelOrderDao.update(channelOrder);
	}

	@Override
	public ProductPackage getProductPackage(String channelOrderId) {
		return productPackageDao.get("channelOrderId", channelOrderId);
	}

	/**
	 * 
	 * @param channelOrderId
	 * @param returnState
	 *            退货状态0:未入库1:已入库2:已换货3:已完成
	 * @return
	 * @throws Exception 
	 */
	@Transactional
	@Override
	public String updateProductPackageReturnState(String channelOrderId, String returnState) throws Exception {
		String msg = SZSCMConstant.SUCCESS;
		ChannelOrder channelOrder = channelOrderDao.get("channelOrderId",channelOrderId);
		//channelOrder.setReturnOrder(returnState);
		channelOrder.setReturnState(returnState);
		if(ObjectUtil.eq(returnState, SZSCMConstant.CHANNEL_ORDER_RETURN_STATE_1) && ObjectUtil.eq(channelOrder.getReturnOrder(),SZSCMConstant.CHANNEL_ORDER_RETURN_TYPE_2)){
			channelOrder.setReturnState( SZSCMConstant.CHANNEL_ORDER_RETURN_STATE_4);
		}
		int count = channelOrderDao.updateByChannelOrderId(channelOrder);
		if (count == 0) {
			msg = SZSCMConstant.FAIL;
		}
		return msg;
	}

	@Override
	public PageFinder returnOrderItemPageList(ChannelOrderVo channelOrderVo, PageQuery pageQuery) {
		return channelOrderItemDao.channelOrderItemPaged(channelOrderVo, pageQuery);
	}

	/**
	 * 
	 * @param channelOrderId
	 * @param orderState
	 *            订单状态 0：已提交 1：审核通过 2:审核不通过 3:待支付 4:待发货 5:已发货 6:已完成 7:已取消 8:已锁定
	 *            9部分发货 10已收货 11已关闭
	 * @return
	 */
	@Transactional
	@Override
	public String updateOrderState(String channelOrderId, String orderState) {
		String msg = SZSCMConstant.SUCCESS;
		ChannelOrder channelOrder = new ChannelOrder();
		channelOrder.setChannelOrderId(channelOrderId);
		channelOrder.setOrderState(orderState);
		int count = channelOrderDao.updateByChannelOrderId(channelOrder);
		if (count == 0) {
			msg = SZSCMConstant.FAIL;
		}
		return msg;
	}
	
	public Boolean saveChannelOrder(JSONArray jsonArray) throws Exception{
		List<ChannelOrder> chanelList = arrayJSONToChanel(jsonArray);
		if(chanelList.size()>0){
			ChannelOrder chanel = new ChannelOrder();
			ChannelOrderReceiver receiver = new ChannelOrderReceiver();
			ChannelOrderItem item = new ChannelOrderItem();
			for (ChannelOrder channelOrder : chanelList) {
				chanel.setChannelOrderId(channelOrder.getChannelOrderId());
				chanel.setOrderType(channelOrder.getOrderType());
				chanel.setReturnState(channelOrder.getReturnState());
				chanel.setOrderTotalPrice(Double.valueOf(channelOrder.getOrderTotalPrice()));
				chanel.setReceiverName(channelOrder.getReceiverName());
				chanel.setOrderState(channelOrder.getOrderState());
				chanel.setPayType(channelOrder.getPayType());
				chanel.setReceiverPhone(channelOrder.getReceiverPhone());
				chanel.setDeliveryState(channelOrder.getDeliveryState());
				chanel.setReturnOrder(channelOrder.getReturnOrder());
				chanel.setOrderStartTime(channelOrder.getOrderStartTime());
				chanel.setOrderRemark(channelOrder.getOrderRemark());
				chanel.setPayState(channelOrder.getPayState());
				chanel.setChannelOrderType(channelOrder.getChannelOrderType());
				try {
					channelOrderDao.save(chanel);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			
			
		}else{
			return false;
		}
		return false;
	}

	private List<ChannelOrder> arrayJSONToChanel(JSONArray jsonArray) {
		List<ChannelOrder> chanelList = new ArrayList<>();
		if(jsonArray.size()!=0 ){
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject jsonJ = jsonArray.getJSONObject(i);
				ChannelOrder chanel = new ChannelOrder();
				chanel.setChannelOrderId(getString(jsonJ,"channelOrderId"));
				chanel.setOrderType(getString(jsonJ, "orderType"));
				chanel.setReturnState(getString(jsonJ, "returnState"));
				chanel.setOrderTotalPrice(Double.valueOf(getString(jsonJ, "orderTotalPrice")));
				chanel.setReceiverName(getString(jsonJ, "receiverName"));
				chanel.setOrderState(getString(jsonJ, "orderState"));
				chanel.setPayType(getString(jsonJ, "payType"));
				chanel.setReceiverPhone(getString(jsonJ, "receiverPhone"));
				chanel.setDeliveryState(getString(jsonJ, "deliveryState"));
				chanel.setReturnOrder(getString(jsonJ, "returnOrder"));
				chanel.setOrderStartTime(getString(jsonJ, "orderStartTime"));
				chanel.setOrderRemark(getString(jsonJ, "orderRemark"));
				chanel.setPayState(getString(jsonJ, "payState"));
				chanel.setChannelOrderType(getString(jsonJ, "channelOrderType"));
				
				JSONObject orderReceiverJ = jsonJ.getJSONObject("orderReceiver");
				ChannelOrderReceiver receiver = new ChannelOrderReceiver();
				if(orderReceiverJ!=null){
					receiver.setChannelOrderId(getString(orderReceiverJ,"channelOrderId"));
					receiver.setProvince(getString(orderReceiverJ, "province"));
					receiver.setCity(getString(orderReceiverJ, "city"));
					receiver.setCounty(getString(orderReceiverJ, "county"));
					receiver.setFullAddress(getString(orderReceiverJ, "fullAddress"));
					receiver.setMobile(getString(orderReceiverJ, "mobile"));
					receiver.setTelephone(getString(orderReceiverJ, "telephone"));
					receiver.setFullname(getString(orderReceiverJ, "fullname"));
				}
				try {
					channelOrderReceiverDao.save(receiver);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				/*放开chanel.setOrderReceiver(receiver);*/
				
				Set<ChannelOrderItem> items = new HashSet<ChannelOrderItem>();
				JSONArray orderItems=jsonJ.getJSONArray("orderItems");
				if(orderItems!=null){
					for (int j = 0; j < orderItems.size(); j++) {
						JSONObject jsonI = orderItems.getJSONObject(j);
						ChannelOrderItem item = new ChannelOrderItem();
						item.setChannelOrderId(getString(jsonI,"channelOrderId"));
						item.setSkuName(getString(jsonI, "skuName"));
						item.setItemNum(getString(jsonI, "itemNum"));
						item.setItemTotal(Double.valueOf(getString(jsonI, "itemTotal")));
						item.setItemPrice(Double.valueOf(getString(jsonI, "itemPrice")));
						item.setSkuId(getString(jsonI, "skuId"));
						try {
							channelOrderItemDao.save(item);
						} catch (Exception e) {
							e.printStackTrace();
						}
						items.add(item);
						chanel.setOrderItems(items);
					}
				}
				chanelList.add(chanel);
			}
		}
		return chanelList;
	}
	
	public String getString(JSONObject json,String key){
		if(json.containsKey(key)){
			return json.getString(key);
	    }
		return null;
	}
	
	/**
     * 
     * @Title: addPurchase
     * @Description: 单个增加多渠道订单
     * @param brandVo
     * @return
	 * @throws Exception 
     * @throws
     * @author: Liangshunwang
     * @date: 2013-5-26下午04:17:40
     */
	@Override
	public void addPurchaseReturn(List<ChannelOrderItem> purchase,ChannelOrderReceiver channelOrderReceiver,ChannelOrder order) throws Exception {
		ChannelOrderItem channelOrderItem = new ChannelOrderItem();//商品
		ChannelOrder channelOrder = new ChannelOrder();//支付方式
		ChannelOrderReceiver channelReceiver = new ChannelOrderReceiver();//收货人
		if(purchase.size()!=0 && channelOrderReceiver!=null && order !=null){
			for (ChannelOrderItem purch : purchase) {
				channelOrderItem.setChannelOrderId(NoUtil.getNo("CH"));
				channelOrderItem.setItemTotal(purch.getItemTotal());
				channelOrderItem.setItemPrice(purch.getItemPrice());
				channelOrderItem.setSkuName(purch.getSkuName());
				try{
					channelOrderItemDao.save(channelOrderItem);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			//支付方式
			channelOrder.setChannelOrderId(channelOrderItem.getChannelOrderId());
			channelOrder.setChannelOrderType(order.getChannelOrderType());
			channelOrder.setOrderState(order.getOrderState());
			channelOrder.setDeliveryState(order.getDeliveryState());
			channelOrder.setPayState(order.getPayState());
			channelOrder.setPayType(order.getPayType());
			channelOrder.setOrderType(order.getOrderType());
			channelOrder.setOrderTotalPrice(channelOrderItem.getItemPrice());//货品总价格
			channelOrder.setOrderStartTime(DateUtil.formatTimesTampDate(new Date()));
			channelOrder.setReturnOrder(order.getReturnOrder());
			channelOrder.setReturnState(order.getReturnState());
			channelOrder.setReceiverName(channelOrderReceiver.getFullname());
			channelOrder.setReceiverPhone(channelOrderReceiver.getTelephone());
			//收货人资料
			channelReceiver.setChannelOrderId(channelOrderItem.getChannelOrderId());
			channelReceiver.setFullname(channelOrderReceiver.getFullname());
			channelReceiver.setTelephone(channelOrderReceiver.getTelephone());
			channelReceiver.setMobile(channelOrderReceiver.getMobile());
			channelReceiver.setProvince(channelOrderReceiver.getProvince());
			channelReceiver.setCity(channelOrderReceiver.getCity());
			channelReceiver.setCounty(channelOrderReceiver.getCounty());
			channelReceiver.setFullAddress(channelOrderReceiver.getFullAddress());
			try{
				channelOrderReceiverDao.save(channelReceiver);
				channelOrderDao.save(channelOrder);
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
}